# coding:utf-8
import json
from typing import Callable, Dict
from PyQt6.QtCore import QUrl
from PyQt6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout
from qframelesswindow.webengine import FramelessWebEngineView

from common.utils.utils_log import AntLogger
from views.common.static_path_helper import StaticPathHelper


class MainEchatTemplate(QWidget):
    """通用图表创建类"""

    def __init__(
        self,
        parent,
        chatName: str,
        dataFun: Callable[[str, Dict[str, str]], str],
        datParamFun: Callable[[], Dict[str, str]],
    ):
        super().__init__()
        self.dataFun = dataFun
        self.datParamFun = datParamFun
        self.chatName = chatName
        self.setMinimumWidth(500)
        self.setMinimumHeight(500)
        self.init_ui()

    def init_ui(self):
        # 水平视图 ： Chat 默认以水平试图分为左右两个部分
        self.viewLayout = QHBoxLayout()

        # 左侧为Echat 图表
        self.chatLeftLayout = QVBoxLayout()
        self.webView = FramelessWebEngineView(self)
        self.chatLeftLayout.addWidget(self.webView)

        # 调用方法完成布局
        self.setup_layout()

        # 刷新 Echat
        self.do_load_chat()

    def setup_layout(self):
        # 将左侧和右侧布局作为小部件添加到 viewLayout
        left_widget = QWidget()
        left_widget.setLayout(self.chatLeftLayout)

        # 设置左侧最小宽度和高度
        left_widget.setMinimumWidth(300)  # 设置最小宽度为 300 像素
        left_widget.setMinimumHeight(400)  # 设置最小高度为 400 像素

        # 添加左右布局到水平布局
        self.viewLayout.addWidget(left_widget)

        # 设置 viewLayout 为当前窗口的主布局
        self.setLayout(self.viewLayout)

    def do_load_chat(self):
        # 获取HTML文件路径
        html_path = StaticPathHelper.get_html_resource_path(self.chatName)
        
        # 确保资源目录存在
        if not StaticPathHelper.ensure_resource_exists(html_path):
            AntLogger.error(f"HTML template not found: {html_path}")
            return
            
        # 加载HTML文件
        self.webView.load(QUrl.fromLocalFile(str(html_path)))
        self.webView.loadFinished.connect(self.do_load_data)

    def do_load_data(self):
        # 获取JSON文件路径
        json_path = StaticPathHelper.get_json_resource_path(self.chatName)
        
        # 确保资源目录存在
        if not StaticPathHelper.ensure_resource_exists(json_path):
            AntLogger.error(f"JSON template not found: {json_path}")
            return
            
        try:
            # 读取JSON文件
            with open(json_path, "r", encoding="utf-8") as file:
                json_data = json.load(file)

            # 调用函数方法进行解析
            chatData = self.dataFun(json_data, self.datParamFun())

            # 执行JavaScript
            js_code = f"setData({chatData});"
            AntLogger.debug(f"最终写入参数: {js_code}")
            self.webView.page().runJavaScript(js_code, self.echat_callback)
            
        except FileNotFoundError:
            AntLogger.error(f"无法找到JSON文件: {json_path}")
        except json.JSONDecodeError:
            AntLogger.error(f"JSON文件格式错误: {json_path}")
        except Exception as e:
            AntLogger.error(f"加载数据时发生错误: {str(e)}")

    def echat_callback(self, result):
        AntLogger.info(f"JavaScript执行结果: {result}")

    def add_right_layout(self, widget: QWidget):
        self.rightLayout.widget(widget)

    def refreshData(self):
        self.do_load_data() 